package com.jiao.datasource.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.jiao.datasource.parse.SQLCommand;
import java.sql.Connection;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description
 * @Author Vincent.jiao
 * @Date 2022/5/13 11:25
 */
public class ListenerExce {
    /** 监听器集合 */
    public static final List<SQLListener> sqlListenerList = new LinkedList<>();
    public static final List<ConnectionListener> connListenerList = new LinkedList<>();

    public static void registerSQLListeners(SQLListener sqlListener) {
        sqlListenerList.add(sqlListener);
    }

    public static void registerSQLListeners(Collection<SQLListener> colls) {
        sqlListenerList.addAll(colls);
    }

    public static void registerConnListener(ConnectionListener connListener) {
        connListenerList.add(connListener);
    }
    public static void registerConnListener(Collection<ConnectionListener> colls) {
        connListenerList.addAll(colls);
    }

    /**
     * 监听执行 sql 之前操作.
     */
    public static void execBefore(SQLCommand sqlCommand){
        if(CollectionUtil.isNotEmpty(sqlListenerList)) {
            for (SQLListener item : sqlListenerList) {
                item.execBefore(sqlCommand);
            }
        }
    }

    /**
     * 监听 sql 写之后操作.
     */
    public static void execAfter(SQLCommand sqlCommand){
        if(CollectionUtil.isNotEmpty(sqlListenerList)) {
            for (SQLListener item : sqlListenerList) {
                item.execAfter(sqlCommand);
            }
        }
    }

    /**
     * 监听 sql 写操作(commit前).
     */
    public static void commiteBefore(List<SQLCommand> sqlCommands){
        if(CollectionUtil.isNotEmpty(connListenerList)) {
            for (ConnectionListener item : connListenerList) {
                item.commiteBefore(sqlCommands);
            }
        }
    }

    /**
     * 监听 sql 写操作(commit后).
     */
    public static void commiteAfter(List<SQLCommand> sqlCommands){
        if(CollectionUtil.isNotEmpty(connListenerList)) {
            for (ConnectionListener item : connListenerList) {
                item.commiteAfter(sqlCommands);
            }
        }
    }

    /**
     * 关闭链接前.
     */
    public static void close(Connection conn){
        if(CollectionUtil.isNotEmpty(connListenerList)) {
            for (ConnectionListener item : connListenerList) {
                item.close(conn);
            }
        }
    }

    /**
     * 获取连接后事件.
     */
    public static void open(Connection conn){
        if(CollectionUtil.isNotEmpty(connListenerList)) {
            for (ConnectionListener item : connListenerList) {
                item.open(conn);
            }
        }
    }
}
